//
//  DataBaseManager.m
//  VEW
//
//  Created by lanou3g on 15/7/28.
//  Copyright (c) 2015年 Y团. All rights reserved.
//

#import "DataBaseManager.h"
#import "HomeModel.h"


@interface DataBaseManager()

@property (nonatomic,retain)NSMutableArray *array;
@property (nonatomic,retain)HomeModel *home;

@end

@implementation DataBaseManager

static DataBaseManager *handle=nil;

+ (instancetype)shareInstance
{
    //加线程锁保证访问安全
    @synchronized(self){
        if (handle == nil) {
            handle = [[DataBaseManager alloc]init];
            [handle openDB];
        }
        return handle;
    }
}

//声明一个数据库指针,用来操作数据库;
static sqlite3 *db=nil;

//document路径
-(NSString *)documentPath
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
}

//打开数据库
- (void)openDB{
    
    //如果数据库已经打开，则不做任何操作
    if (nil != db) {
        return;
    }
    NSString *dbPath=[[self documentPath] stringByAppendingPathComponent:@"News.sqlite"];
    NSLog(@"%@",dbPath);
    //打开数据库
    int result=sqlite3_open(dbPath.UTF8String, &db);
    //判断是否打开
    if(result==SQLITE_OK)
    {
        NSString * createSql = @"CREATE TABLE IF NOT EXISTS NewsList (MyID TEXT PRIMARY KEY , title TEXT not NULL);";
        sqlite3_exec(db, [createSql UTF8String], NULL, NULL, NULL);
    }
}

//关闭数据库
-(void)closeDB
{
    int result = sqlite3_close(db);
    if (result == SQLITE_OK) {
        db = nil;
    }
}
//
////建表
//-(void)creatTable
//{
//    NSString *sqlWord = @"CREATE TABLE IF NOT EXISTS NewsList  (MyID INTEGER PRIMARY KEY NOT NULL, title TEXT NOT NULL, z_image TEXT NOT NULL)";
//    //2.执行SQL语句
//    int result = sqlite3_exec(db, sqlWord.UTF8String, NULL, NULL, NULL);
//    if (result == SQLITE_OK) {
//        NSLog(@"创建成功!");
//    }else{
//        NSLog(@"创建失败!错误代码是%d",result);
//    }
//
//}
//添加
-(void)insertNews:(HomeModel *)home
{
    [self openDB];
    
    sqlite3_stmt *stmt = nil;
    
    //1.准备SQL语句
    NSString *sqlWord = @"INSERT INTO NewsList (MyID,title) VALUES (?,?)";
    
    //2.执行SQL语句
    int result = sqlite3_prepare_v2(db, [sqlWord UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        
        sqlite3_bind_text(stmt, 1, [home.MyID UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [home.title UTF8String], -1, NULL);
    
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
}

//删除
-(void)deleteNews:(HomeModel *)home
{
    [self openDB];
    sqlite3_stmt * stmt = nil;
    NSString *sqlWord = @"DELETE FROM NewsList WHERE MyID = ?";
    int result = sqlite3_prepare_v2(db, [sqlWord UTF8String], -1, & stmt, NULL);
    if (result == SQLITE_OK) {
        
        sqlite3_bind_text(stmt, 1, [home.MyID UTF8String], -1, NULL);
        
        sqlite3_step(stmt);
    }
    
    sqlite3_finalize(stmt);
}

-(void)deleteAll
{
    [self openDB];
    NSString *sqlWord = @"DELETE TABLE NewsList";
    //2.执行SQL语句
    int result = sqlite3_exec(db, sqlWord.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功!");
    }else{
        NSLog(@"删除失败!错误代码是%d",result);
    }
}

//查找
-(NSArray *)selectAllNews
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:50];
    //准备SQL语句
    NSString *sqlWord = @"SELECT *FROM NewsList";
    //创建伴随指针
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare_v2(db, sqlWord.UTF8String, -1, &stmt, nil);//没有实际操作，只是为下面的操作做准备
    
    if (result == SQLITE_OK) {//判断
        while (sqlite3_step(stmt) == SQLITE_ROW) {//真正的取值操作
            //执行SQL语句
            NSString *MyID=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSString *title=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
           
            HomeModel *home = [HomeModel new];
            home.MyID = MyID;
            home.title =title;
           
            //把值添加到数组
            [array addObject:home];
        }
    }
    //释放伴随指针
    sqlite3_finalize(stmt);
    
    return array;
}

//获取某个新闻
-(HomeModel *)selectWithNewsID:(NSString *)MyID
{
    [self openDB];
   
    NSString * sql = [NSString stringWithFormat:@"select * from NewsList where MyID = '%@'",MyID];
    
    sqlite3_stmt * stmt = nil;
    
     _home = nil;
    
    //3、执行sql语句
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, nil);
    NSMutableArray *array=[NSMutableArray array];
    
    if (result == SQLITE_OK) {
//        sqlite3_bind_int(stmt, 1, MyID);//给问号占位符赋值
        while (sqlite3_step(stmt)==SQLITE_ROW) {
            //取值;当我们没有自增id,数据表会给我们生成rowid字段,但是这个rowid字段没有算在表的字段内;
            NSString *MyID=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSString *title=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            
            _home = [[HomeModel alloc]init];
            _home.MyID = MyID;
            _home.title =title;
            
            //把值添加到数组
            [array addObject:_home];
        }
    }
    //释放伴随指针
    sqlite3_finalize(stmt);
    
    return _home;
}



//判断活动是否被收藏
- (BOOL)isCollectNewsWithID:(NSString *)MyID
{
    HomeModel * home = [self selectWithNewsID:MyID];
    if (home == nil)
    {
        return NO;
    }
    else
    {
    return YES;
    }
}


//收藏
-(NSInteger)countOfNews
{
    return [self.array count];
}
//获取某个活动对象
-(HomeModel *)newsForRow:(NSInteger)row
{
    return _array[row];
}

-(void)deleteNewsForRow:(NSInteger)row
{
    [[DataBaseManager shareInstance] deleteNews:[self newsForRow:row]];
    [_array removeObjectAtIndex:row];
}

//-(void)setupNewsDataSource{
//    self.array=[[[DataBaseManager shareInstance]selectAllNews]mutableCopy];
//}

@end
